import React from 'react';
import RcUpload from 'rc-upload';
import { Button,  Message } from '../../../../components';
import * as cache from '../../../../utils/cache';
import './uploadFile.less';
import urlPrefix from '../../../.././utils/constants'

/**
 * 上传
 */
export default class UploadFile extends React.Component {
  constructor(props) {
    super(props)
    const { value } = this.props
    this.state = {
      value,
      loading: false,
      fileList: [],
      data:{
        moduleName: '',
        dbType: ''
      }
    }

    this.uploaderProps = {
      accept: '*',
      action: `${urlPrefix.urlPrefix}/project/ddl/${cache.getItem('projectId')}`,
      headers: {
        'Authorization': `Bearer ${cache.getItem('Authorization')}`,
      },
      onStart: () => {
        if (!cache.getItem('projectId')) {
          Message.warning({ message: '请刷新页面再试！' });
          return;
        }
        this.setState({ loading: true })
      },
      onSuccess: (file, source = {}) => {
        Message.success({ title: `${source.name}导入成功` })
        this.props.onSuccess()
        let { fileList } = this.state;
        if (source?.name) { 
          fileList.push(source.name)
        }
        this.setState({ loading: false, fileList })
      },
      onProgress(step, file) {
      },
      onError: (err, response = {}) => {
        const { emsg } = response
        if (emsg) {
          Message.warning({ message: emsg })
        }
        this.setState({ loading: false })
      },
    }
  }

  componentDidMount() {
    this.setState({ data: this.props.data})
  }
  
  render() {
    const { fileList, loading, data } = this.state
    const { value, accept = 'image', btText = '选择图片', hint = '请上传jpg、png、gif格式的图片，大小在5M以内', disabled = false } = this.props;
    return (
      <div className="ddl-upload" style={{display: 'inline-block' }}>
        <div className="block">
          {accept == 'image' && <img src={value} style={{ background: value ? 'transparent' : '#F2F2F2' }} />}
          <RcUpload {...this.uploaderProps} data={data} className={disabled ? 'disabled-rc' : ''} disabled={disabled} style={{ marginTop: '20px', }}>
            <Button className="tc-15-btn weak" loading={loading}>{btText}</Button>
          </RcUpload>
        </div>
        {accept != 'image' && <div className="file-path" title={value}>{value}</div>}
        <div>{hint}</div>
        {fileList.length > 0 && <div style={{ marginTop: '20px'}}>{fileList.join(',')}&nbsp;{fileList.length}个文件上传成功</div>}
      </div >
    )
  }
}
